﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Threading;
using System.Diagnostics;

namespace DIfmClient
{
    enum PlayButtonState
    {
        Play,
        Pause,
        Stop
    }

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private DispatcherTimer dt;
        private Channel c;
        private List<Track> Tracklist;

        public MainWindow()
        {
            InitializeComponent();

            dt = new DispatcherTimer();
            dt.Tick += new EventHandler(dt_Tick);
            dt.Interval = new TimeSpan(0, 0, 5);

            labelAppName.Content = ConfigurationManager.AppSettings["appLabel"] + " v1.0.0.2" /*+ Assembly.GetExecutingAssembly().GetName().Version*/;
            AudioFormat audioFormat = AudioFormat.wma40;
            List<Channel> channelList = new List<Channel>();

            try
            {
                channelList = ListManager.RetrieveChannels(ConstructJsonUrl(audioFormat));
                listBoxChannels.DataContext = channelList;
            }
            catch (Exception)
            {
                throw;
            }
        }

        private static string ConstructJsonUrl(AudioFormat audioFormat)
        {
            return ConfigurationManager.AppSettings["jsonapi"] + "/" + ConfigurationManager.AppSettings["" + audioFormat];
        }

        private void btnPlay_Click(object sender, RoutedEventArgs e)
        {
            if ((PlayButtonState)btnPlay.Content == PlayButtonState.Play)
            {
                c = new Channel();
                c = (Channel)listBoxChannels.SelectedItem;

                Tracklist = new List<Track>();
                Tracklist = ListManager.RetrievePlaylist(ConfigurationManager.AppSettings["trackHistory"], c);

                listBoxPlaylist.DataContext = Tracklist;

                if (c != null)
                {
                    dt.Start();
                    btnPlay.Content = PlayButtonState.Stop;
                    Uri u = new Uri(c.Playlist.Substring(0, c.Playlist.Length-3) + "asx");
                    me.Source = u;
                    me.LoadedBehavior = MediaState.Play;
                }
            }
            else
            {
                btnPlay.Content = PlayButtonState.Play;
                me.LoadedBehavior = MediaState.Stop;
                dt.Stop();
            }
        }

        void dt_Tick(object sender, EventArgs e)
        {
            progressBarBuffer.Value = me.BufferingProgress * 100;
            progressBarBuffer.UpdateLayout();

            Tracklist = ListManager.RetrievePlaylist(ConfigurationManager.AppSettings["trackHistory"], c);
        }

        void me_BufferingStarted(object sender, RoutedEventArgs e)
        {
            dt.Start();
        }

        void me_BufferingEnded(object sender, RoutedEventArgs e)
        {
            dt.Stop();
        }

        private void Window_DragEnter(object sender, DragEventArgs e)
        {
            e.Effects = DragDropEffects.Move;
        }

        private void labelClose_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        private void labelMinimize_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.WindowState = System.Windows.WindowState.Minimized;
        }

        private void volumeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            me.Volume = volumeSlider.Value;
        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Control src = e.Source as Control;

            if (src != null && e.ChangedButton == MouseButton.Left)
            {
                this.DragMove();
            }
        }

        private void listBoxChannels_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if ((Channel)listBoxChannels.SelectedItem == c)
            {
                btnPlay.Content = PlayButtonState.Stop;
            }
            else btnPlay.Content = PlayButtonState.Play;
        }

        private void listBoxPlaylist_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {            
            ContextMenu playlistContextMenu = new ContextMenu();
            
            MenuItem searchYouTube = new MenuItem();
            searchYouTube.Header = "Search track on YouTube"; 
            searchYouTube.Click += new RoutedEventHandler(searchYouTube_Click);
            playlistContextMenu.Items.Add(searchYouTube);

            MenuItem searchGoogle = new MenuItem();
            searchGoogle.Header = "Search track on Google";
            searchGoogle.Click += new RoutedEventHandler(searchGoogle_Click);
            playlistContextMenu.Items.Add(searchGoogle);

            playlistContextMenu.IsOpen = true;
        }

        void searchGoogle_Click(object sender, RoutedEventArgs e)
        {
            string url = "http://www.google.com/#hl=en&q=" + listBoxPlaylist.SelectedValue;
            Process.Start(url);
        }

        void searchYouTube_Click(object sender, RoutedEventArgs e)
        {
            string url = "http://www.youtube.com/results?search_query=" + listBoxPlaylist.SelectedValue;
            Process.Start(url);
        }
    }
}
